package me.uniauto.util;

import me.uniauto.util.BusinessDataCode;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

/**
 * Created by hardy on 2018/2/22.
 */
public class CommResp implements Serializable {

    private String code;
    private String message;
    private Object data;


    public static final CommResp success_resp = new CommResp(BusinessDataCode.SUCCESS);
    public static final CommResp fail_resp = new CommResp(BusinessDataCode.FAIL);
    public static final CommResp no_data_resp = new CommResp(BusinessDataCode.NO_DATA);
    public static final CommResp args_error_resp = new CommResp(BusinessDataCode.ARGS_ERROR);
    public static final CommResp service_exception_resp = new CommResp(BusinessDataCode.SERVICE_EXCEPTION);
    public static final CommResp user_not_login = new CommResp(BusinessDataCode.USER_NOT_LOGIN);

    public CommResp() {
        super();
    }

    public CommResp(String code, String message) {
        this.code = code;
        this.message = message;
    }

    public CommResp(String code, String message, String data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public CommResp(BusinessDataCode businessDataCode) {
        this.code = businessDataCode.getCode();
        this.message = businessDataCode.getDesc();
    }

    public CommResp(BusinessDataCode businessDataCode, Object data) {
        this.code = businessDataCode.getCode();
        this.message = businessDataCode.getDesc();
        this.data = data;
    }


    @Override
    public String toString() {
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(BigDecimal.class, new JsonDateValueProcessor());
        if (data instanceof Iterable) {
            return "{\"code\":\"" + code + "\", \"message\":\"" + message + "\", \"data\":" + JSONArray.fromObject(data, jsonConfig).toString() + "}";
        } else {
            return "{\"code\":\"" + code + "\", \"message\":\"" + message + "\", \"data\":" + JSONObject.fromObject(data, jsonConfig).toString() + "}";
        }
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}
